﻿@{
    Layout = "_Layout";
    ViewData["Title"] = "元数据字段表";
}
@section Styles {
    <style>
        .el-dialog__header .el-dialog__body .avue-crud .avue-crud__header {
            min-height: 0px !important;
        }

        div.avue-crud__body:nth-child(1) > div:nth-child(1) > div:nth-child(1) {
            min-height: 0px !important;
        }

        .el-textarea__inner{
        min-height:580px !important;
        }
    </style>
}
<el-container>
    <avue-crud :data="tableData" :option="option" :permission="hasPermission" :page.sync="pageOption" :table-loading="loading"
               v-on:refresh-change="refreshChange"
               v-on:row-save="handleRowSave"
               v-on:row-update="handleRowUpdate"
               v-on:row-del="handleRowDel"
               v-on:search-change="searchChange"
               v-on:search-reset="resetChange"
               v-on:selection-change="selectionDataChange"
               :cell-style="cellStyle"
               v-on:on-load="onLoad">
        <template slot="menuLeft" slot-scope="{size}">
            <el-button type="success" :size="size" v-on:click="Export">导入</el-button>
            @* <el-button type="warning" :size="size" v-on:click="Async">同步</el-button> *@
            <el-button type="primary" :size="size" v-on:click="showTemp">模板代码生成</el-button>
            <el-button type="info" :size="size" v-on:click="showProject">项目代码生成</el-button>
            @* <el-button :size="size">配置</el-button> *@
        </template>

        <template slot="menuBefore" slot-scope="{row,index,size,type}">
            <el-button :size="size" :type="type" v-on:click="buildUrlDialog(row)">模板代码预览</el-button>
            <el-button :size="size" :type="type" v-on:click="openUrlDialog(row)">配置列</el-button>
        </template>

    </avue-crud>

    <el-dialog title="导入" :visible.sync="dialogDragVisible" class="avue-dialog avue-dialog--top" width="40%" dialogDrag="true">
        <el-select v-model="selectDbValue" placeholder="请选择" size="mini" style="width:30%;" v-on:change="selectDbChange" clearable>
            <el-option v-for="item in selectDbData" :key="item.id" :label="item.dbName" :value="item.id"></el-option>
        </el-select>
        <avue-crud ref="crud" :data="selectTableData" :option="selectTableOption" v-on:selection-change="selectionChange"></avue-crud>
        <div class="avue-dialog__footer">
            <el-button @@click="dialogDragVisible=false" size="mini">取 消</el-button>
            <el-button @@click="selectTableDataOk" type="primary" size="mini">确 定</el-button>
        </div>
    </el-dialog>


    <el-dialog title="模板代码预览" :visible.sync="dialogDragBuildVisible" class="avue-dialog avue-dialog--top" width="40%" dialogDrag="true">
        <el-form ref="form" label-width="80px">
            <el-form-item label="模板">
                <el-select v-model="selectTempValue" placeholder="请选择" size="mini" v-on:change="selectTempChange" clearable>
                    <el-option v-for="item in selectTempData" :key="item.id" :label="item.name" :value="item.id" path="item.buildPath"></el-option>
                </el-select>
            </el-form-item>
   
            <el-form-item label="生成地址">
                <el-input size="mini" :value="buildPath"></el-input>
            </el-form-item>
            <div style="color:red;">
                生成地址<br />
                地址说明:修改模版可以修改这个地址 [进入模版管理]<br />
                符号说明:{0}是ClassName, {1}表示TableName,{project}表示项目的sln文件目录<br />
            </div>
        </el-form>
        <div class="avue-dialog__footer">
            <el-button @@click="dialogDragBuildVisible=false" size="mini">取 消</el-button>
            <el-button @@click="viewBuild" type="primary" size="mini">预 览</el-button>
            @* <el-button @@click="codeBuild" type="primary" size="mini">生 成</el-button> *@
        </div>
    </el-dialog>

    <!-- 页面弹窗 -->
    <el-dialog :visible.sync="urlDialogVisible" title="配置列" width="90%" :fullscreen="true">
        <iframe v-if="urlDialogVisible" :src="currentUrl" width="100%" height="900px" frameborder="0"></iframe>
    </el-dialog>

    <el-dialog title="模板代码预览" :visible.sync="dialogTempDataVisible" class="avue-dialog avue-dialog--top" width="40%" dialogDrag="true">
        <el-form ref="form" label-width="80px">
            <el-form-item label="模板">
                <el-select v-model="selectTempValue" placeholder="请选择" size="mini" v-on:change="selectTempChange" clearable>
                    <el-option v-for="item in selectTempData" :key="item.id" :label="item.name" :value="item.id" path="item.buildPath"></el-option>
                </el-select>
            </el-form-item>
            <div style="color:red;">
                生成地址<br />
                地址说明:修改模版可以修改这个地址 [进入模版管理]<br />
                符号说明:{0}是ClassName, {1}表示TableName,{project}表示项目的sln文件目录<br />
            </div>
        </el-form>
        <div class="avue-dialog__footer">
            <el-button @@click="dialogTempDataVisible=false" size="mini">取 消</el-button>
            <el-button @@click="BuildCodeTemp" type="primary" size="mini">生成并下载</el-button>
        </div>
    </el-dialog>

    <el-dialog title="项目代码预览" :visible.sync="dialogProjectDataVisible" class="avue-dialog avue-dialog--top" width="40%" dialogDrag="true">
        <el-form ref="form" label-width="80px">
            <el-form-item label="项目">
                <el-select v-model="selectProjectValue" placeholder="请选择" size="mini" v-on:change="selectProjectChange" clearable>
                    <el-option v-for="item in selectProjectData" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <div style="color:red;">
                生成地址<br />
                地址说明:修改模版可以修改这个地址 [进入模版管理]<br />
                符号说明:{0}是ClassName, {1}表示TableName,{project}表示项目的sln文件目录<br />
            </div>
        </el-form>
        <div class="avue-dialog__footer">
            <el-button @@click="dialogProjectDataVisible=false" size="mini">取 消</el-button>
            <el-button @@click="BuildCodeProject" type="primary" size="mini">生成并下载</el-button>
        </div>
    </el-dialog>
</el-container>

@section Scripts {
    <script>
        new Vue({
            el: '#app',
            mixins: [curdMixin],
            data() {
                return {

                    name: "TableMetadata",
                    pageUrl: `/TableMetadata/pages`,
                    addUrl: `/TableMetadata/add`,
                    editUrl: `/TableMetadata/update`,
                    deleteUrl: `/TableMetadata/delete`,
                    dialogDragVisible: false,
                    option: {
                        searchShowBtn: Permissions.avePermission(`TableMetadata:searchBtn`),
                        refreshBtn: Permissions.avePermission(`TableMetadata:searchBtn`),
                        menuWidth: '350',
                        rowKey: 'id',
                        searchShow: false,
                        viewBtn: false,
                        columnBtn: false,
                        selection:true,
                        column: [
                            { prop: "id", label: `${this.i18n.t('primary_key')}`, search: false, hide: true, type: "number", display: false, showColumn: false, },
                            { prop: "dbId", label: `数据库`, slot: true, search: true, type: 'select', span: 24, hide: false, width: '220', dicUrl: "/DbConnStrInfo/list", props: { label: "dbName", value: "id", }, clearable: true, rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseenter')}` }], },
                            { prop: "tableName", label: `表名`, slot: true, search: true, span: 24, hide: false, width: '220', clearable: true, rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseenter')}` }], },
                            { prop: "className", label: `实体名`, slot: true, search: true,  span: 24,hide: false, width: '220', clearable: true, rules: [{ required: true, trigger: "blur", message: `${this.i18n.t('pleaseenter')}` }], },
                            { prop: "description", label: `表备注`, type: 'textarea', hide: false, showColumn: false, span: 24, rows: 2, },
                        ],
                    },

                    selectDbData:[],
                    selectDbValue:null,

                    selectTableData:[],
                    selectTableValue:[],
                    selectTableOption:{
                        menu:false,
                        addBtn:false,
                        columnBtn:false,
                        selection: true,
                        column:[
                          { label:'表名', prop:'name' },
                          { label:'说明', prop:'description'}
                        ]
                    },

                    urlDialogVisible: false,
                    currentPath: '/FieldMetadata/index?tableId=',
                    currentUrl: '',

                    dialogDragBuildVisible:false,

                    selectTempValue:{},
                    selectTempData:[],
                    buildPath:"",
                    selectList:[],
                    selectDataList:[],

                    dialogTempDataVisible:false,
                    dialogProjectDataVisible:false,

                    selectProjectData:[],
                    selectProjectValue:"",
                }
            },
            created() {
                this.loadSelectDbData();
                this.loadselectTempData();
                this.loadselectProjectData();
                this.selectRow = {};
            },
            methods: {
                Export(){
                    this.dialogDragVisible=true;
                    this.loadSelectDbData();
                },
                loadSelectDbData(){
                    this.selectDbData=[];
                     this.$http.get(`/DbConnStrInfo/list`).then((res) => {
                            this.selectDbData = res || [];
                            this.loading = false;
                        }).catch(e => {
                            this.loading = false;
                            console.log(e);
                        });
                },
                selectionDataChange(data){
                    this.selectDataList=data;
                },
                selectionChange(data){
                    this.selectList=data;
                },
                selectDbChange(value) {
                    this.selectDbValue=value;
                    this.loadSelectTableData(value);
                },
                loadSelectTableData(v){
                    this.selectDbData=[];
                    this.$http.get(`/TableMetadata/TableDatas?dbId=`+v).then((res) => {
                           this.selectTableData = res || [];
                           this.loading = false;
                       }).catch(e => {
                           this.loading = false;
                           console.log(e);
                       });
                },
                selectionChange(selection) {
                    this.selectTableValue=selection;
                },
                selectTableDataOk(){
                    this.loading = true;
                    if (this.selectTableValue === null || this.selectTableValue.length === 0) {
                        this.$message({ message: `请选择表`, center: true, type: 'error' });
                    }
                    else{
                         this.$http.post(`/TableMetadata/InitMetadataData`,{dbId:this.selectDbValue,dbTableInfos:this.selectTableValue}).then((res) => {
                             if(!res){
                                 this.$message({ message: `导入成功`, center: true, type: 'success' });
                                 this.searchChange();
                                 this.loading = false;
                             }else{
                                 this.searchChange();
                                 this.loading = false;
                             }
                         }).catch(e => {
                             this.loading = false;
                             console.log(e);
                         });

                         this.dialogDragVisible=false;
                    }
                },
                openUrlDialog(row) {
                  this.currentUrl =this.currentPath+ row.id; // 设置当前 URL
                  this.urlDialogVisible = true; // 打开弹窗
                },
                buildUrlDialog(row){
                    this.dialogDragBuildVisible=true;
                    this.selectRow =row;
                    this.selectTempValue=null;
                },
                Async(){

                },
                loadselectTempData(){
                    this.selectTempData=[];
                     this.$http.get(`/FileTemplate/list`).then((res) => {
                            this.selectTempData = res|| [];
                            this.selectTempValue=this.selectTempData[0].id
                            this.buildPath=this.selectTempData[0].buildPath
                            this.loading = false;
                        }).catch(e => {
                            this.loading = false;
                            console.log(e);
                        });
                },
                loadselectProjectData(){
                    this.selectProjectData=[];
                     this.$http.get(`/projectInfo/list`).then((res) => {
                            this.selectProjectData = res|| [];
                            this.selectProjectValue=this.selectProjectData[0].id
                            this.loading = false;
                        }).catch(e => {
                            this.loading = false;
                            console.log(e);
                        });
                },
                selectTempChange(selection){
                    this.selectTempValue=selection;
                     var tempValue = this.selectTempData.find(x => x.id == selection) || {};
                     this.buildPath=tempValue.buildPath;
                },
                selectProjectChange(selection)
                {
                    this.selectProjectValue=selection;
                },
                viewBuild(){
                    if(! this.selectTempValue)
                    {
                        this.$message({ message: `请先选择模板`, center: true, type: 'warning' });
                        return false;
                    }
                     this.$http.post(`/TableMetadata/codeBuild`,{templateId:this.selectTempValue,configId:this.selectRow.dbId,tableName:this.selectRow.tableName})
                     .then((res) => {
                     this.$DialogForm.show({
                          title: '预览实体',
                          width: '95%',
                          fullscreen:true,
                          data: { content:res },
                          option: {
                              labelWidth:0,
                              submitBtn:false,
                              span:24,
                              column: [
                                {prop: "content",type:'textarea',rows:50 }
                              ]
                          },
                          callback:(res)=>{ /* res.close() */ }
                         })
                     }).catch(e => {
                        this.loading = false;
                        console.log(e);
                    });
                },
                codeBuild(){
                    if(! this.selectTempValue)
                    {
                        this.$message({ message: `请先选择模板`, center: true, type: 'warning' });
                        return false;
                    }
                     this.$http.post(`/TableMetadata/codeBuild`,{templateId:this.selectTempValue,configId:this.selectRow.dbId,tableName:this.selectRow.tableName,buildPath:this.buildPath})
                     .then((res) => {
                          if(!res)
                             this.$message({ message: `生成成功`, center: true, type: 'success' });
                     }).catch(e => {
                        this.loading = false;
                        console.log(e);
                    });
                },
                cellStyle({ row, column, rowIndex, columnIndex }) {
                    if (columnIndex == 7) {
                        if (row.isDisable == 0) {
                            return { color: '#409eff', }
                        }
                        else {
                            return { color: '#f56c6c', }
                        }
                    }
                },
                showTemp(){
                    if (!this.selectDataList || this.selectDataList.length == 0)
                    {
                        this.$message({ message: `请先选择实体模型`, center: true, type: 'warning' });
                        return false;
                    }
                    
                    this.dialogTempDataVisible=true;
                     
                },
                BuildCodeTemp() {
                    if (!this.selectTempValue) {
                        this.$message({ message: `请先选择模板`, center: true, type: 'warning' });
                        return false;
                    }
    
                    this.loading = true;
    
                    // 创建请求数据
                    const requestData = {
                        id: this.selectTempValue,
                        tableInfos: this.selectDataList || []
                    };
    
                    fetch('/TableMetadata/codeBuildByTemp', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestData)
                    })
                    .then(response => {
                        if (!response.ok) {
                            return response.json().then(errorData => {
                                throw new Error(errorData.message || errorData.error || '生成失败');
                            });
                        }
                        return response.blob();
                    })
                    .then(blob => {
                        // 创建下载链接
                        const url = window.URL.createObjectURL(blob);
                        const link = document.createElement('a');
                        link.href = url;
        
                        // 生成文件名
                        const fileName = `code_template_${new Date().getTime()}.zip`;
                        link.download = fileName;
        
                        document.body.appendChild(link);
                        link.click();
        
                        // 清理
                        window.URL.revokeObjectURL(url);
                        document.body.removeChild(link);
        
                        this.$message({ 
                            message: `代码生成成功，文件已开始下载`, 
                            center: true, 
                            type: 'success' 
                        });
        
                        this.loading = false;
                    })
                    .catch(error => {
                        console.error('生成代码失败:', error);
                        this.$message({ 
                            message: error.message || '生成失败，请检查网络连接', 
                            center: true, 
                            type: 'error' 
                        });
                        this.loading = false;
                    });
                },
                showProject(){
                    if (!this.selectDataList || this.selectDataList.length == 0)
                    {
                        this.$message({ message: `请先选择实体模型`, center: true, type: 'warning' });
                        return false;
                    } 
                    this.dialogProjectDataVisible=true;
                      
                },
                BuildCodeProject(){
                    // if(! this.selectProjectValue)
                    // {
                    //     this.$message({ message: `请先选择项目`, center: true, type: 'warning' });
                    //     return false;
                    // }
                    // this.$http.post(`/TableMetadata/codeBuildByProject`, { id: this.selectProjectValue, tableInfos: this.selectDataList, })
                    //  .then((res) => {
                    //       if(!res)
                    //          this.$message({ message: `生成成功`, center: true, type: 'success' });
                    //  }).catch(e => {
                    //     this.loading = false;
                    //     console.log(e);
                    // });

                    if (!this.selectProjectValue) {
                        this.$message({ message: `请先选择项目`, center: true, type: 'warning' });
                        return false;
                    }

                    this.loading = true;

                    // 创建请求数据
                    const requestData = {
                        id: this.selectProjectValue,
                        tableInfos: this.selectDataList || []
                    };

                    fetch('/TableMetadata/codeBuildByProject', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestData)
                    })
                        .then(response => {
                            if (!response.ok) {
                                return response.json().then(errorData => {
                                    throw new Error(errorData.message || errorData.error || '生成失败');
                                });
                            }
                            return response.blob();
                        })
                        .then(blob => {
                            // 创建下载链接
                            const url = window.URL.createObjectURL(blob);
                            const link = document.createElement('a');
                            link.href = url;

                            // 生成文件名
                            const fileName = `code_template_${new Date().getTime()}.zip`;
                            link.download = fileName;

                            document.body.appendChild(link);
                            link.click();

                            // 清理
                            window.URL.revokeObjectURL(url);
                            document.body.removeChild(link);

                            this.$message({
                                message: `代码生成成功，文件已开始下载`,
                                center: true,
                                type: 'success'
                            });

                            this.loading = false;
                        })
                        .catch(error => {
                            console.error('生成代码失败:', error);
                            this.$message({
                                message: error.message || '生成失败，请检查网络连接',
                                center: true,
                                type: 'error'
                            });
                            this.loading = false;
                        });
                },

            }
        });
    </script>

}